package com.controller;

import com.api.UserService;
import com.entity.TokenEntity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册接⼝口，true成功，false失败
     *
     * @param email
     * @param password
     * @param code
     * @return
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public Integer register(@PathVariable String email, @PathVariable String password, @PathVariable String code, HttpServletResponse response) {
        Integer register = userService.register(email, password, code);
        return register;
    }

    /**
     * 登录接⼝口，验证⽤用户名密码合法性，根据⽤用户名和
     * 密码⽣生成token，token存⼊入数据库，并写⼊入cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚页
     *
     * @param email
     * @param password
     * @return
     */
    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable String email, @PathVariable String password, HttpServletResponse response) {
        TokenEntity login = userService.login(email, password);
        setCookie(response, "token", login.getToken());
        return login.getEmail();
    }

    /**
     * 根据token查询⽤用户登录邮箱接⼝
     *
     * @param token
     * @return
     */
    @GetMapping("/info/{token}")
    public String info(@PathVariable String token) {
        TokenEntity tokenEntity = userService.info(token);
        return tokenEntity.getEmail();
    }

    public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value) {
        // new一个Cookie对象,键值对为参数
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(3600);
        // 将Cookie添加到Response中,使之生效
        cookie.setPath("/");
        //cookie.setSecure(true);
        response.addCookie(cookie); // addCookie后，如果已经存在相同名字的cookie，则最新的覆盖旧的cookie
        return response;
    }
}
